package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XiaoAnFenQiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 小安分期
 *
 * https://api.longzankeji.cn/apinotice/merchant/notifyResult/94
 *
 * http://apitest.koukoudai.shop/apinotice/merchant/notifyResult/94
 *
 */
@Service
public class XiaoAnFenQiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        if(StrUtil.isEmpty(memberSourceInfo.getRealname())){
            return pushApiResult;
        }

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase();
//        String idCardMd5 = SecureUtil.md5(memberSourceInfo.getIdcard()).toLowerCase();



        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("nameMd5", nameMd5);
        bizMap.put("age", memberSourceInfo.getAge());
//        bizMap.put("idCardMd5", idCardMd5);
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("socialSecurity", XiaoAnFenQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFund", XiaoAnFenQiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("carProduction", XiaoAnFenQiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("estate", XiaoAnFenQiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("unitSocialSecurity", XiaoAnFenQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("sesame", XiaoAnFenQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("professionalIdentity", XiaoAnFenQiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("customerCreditCard", 1);
        bizMap.put("highestEducation", XiaoAnFenQiUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("monthlyIncome", XiaoAnFenQiUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("customerFormOfPayroll", 1);
        bizMap.put("lengthOfService", 3);
        bizMap.put("loanPurpose", XiaoAnFenQiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("deviceType", 0);
        bizMap.put("channelSignature", pushApiKeyParam.getApiCode());


        log.info("【小安分期】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【小安分期】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            Boolean data = resultObject.getBoolean("data");
            if(data){
                pushApiResult.setPushSuccess(true);
                return pushApiResult;
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("age", memberSourceInfo.getAge());
//        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode", memberSourceInfo.getCityCode());
        paramMap.put("socialSecurity", XiaoAnFenQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XiaoAnFenQiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XiaoAnFenQiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XiaoAnFenQiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XiaoAnFenQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XiaoAnFenQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XiaoAnFenQiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard", 1);
        paramMap.put("highestEducation", XiaoAnFenQiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XiaoAnFenQiUtil.getshouru(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 3);
        paramMap.put("loanPurpose", XiaoAnFenQiUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("deviceType", 0);
        paramMap.put("channelSignature", pushApiKeyParam.getApiCode());


        log.info("【小安分期】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【小安分期】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean state = data.getBoolean("state");
            if(state){
                String url = data.getString("url");
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setApproveUrl(url);
                pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String phoneMd5 = jsonObject.getString("phoneMd5");
        noticeParamDTO.setOutOrderNo(phoneMd5);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

}
